// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package badger_dao_impl

import (
	"context"
	"path/filepath"
	"sort"

	"gitcode.com/openseaotter/so_proto_gen_go.git/image_group_api"
	"gitcode.com/openseaotter/so_server/storage/core"
	"gitcode.com/openseaotter/so_server/utils"
	"github.com/dgraph-io/badger/v4"
	"google.golang.org/protobuf/proto"
)

type ImageGroupList []*image_group_api.ImageGroupInfo

func (a ImageGroupList) Len() int           { return len(a) }
func (a ImageGroupList) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ImageGroupList) Less(i, j int) bool { return a[i].CreateTime < a[j].CreateTime }

type _ImageGroupDao struct {
	dbh *badger.DB
}

func NewImageGroupDao() (core.ImageGroupDao, error) {
	dbPath := filepath.Join(utils.DATA_DIR_PATH, "group")
	options := badger.DefaultOptions(dbPath)
	dbh, err := badger.Open(options)
	if err != nil {
		return nil, err
	}
	return &_ImageGroupDao{dbh: dbh}, nil
}

func (db *_ImageGroupDao) Insert(ctx context.Context, group *image_group_api.ImageGroupInfo) error {
	return db.Update(ctx, group)
}

func (db *_ImageGroupDao) Exist(ctx context.Context, groupName string) (bool, error) {
	txn := db.dbh.NewTransaction(false)
	defer txn.Discard()

	item, err := txn.Get([]byte(groupName))
	if err != nil {
		if err == badger.ErrKeyNotFound {
			return false, nil
		}
		return false, err
	}
	if item.IsDeletedOrExpired() {
		return false, nil
	}
	return true, nil
}

func (db *_ImageGroupDao) Get(ctx context.Context, groupName string) (*image_group_api.ImageGroupInfo, error) {
	txn := db.dbh.NewTransaction(false)
	defer txn.Discard()

	item, err := txn.Get([]byte(groupName))
	if err != nil {
		return nil, err
	}
	if item.IsDeletedOrExpired() {
		return nil, badger.ErrKeyNotFound
	}
	value, err := item.ValueCopy(nil)
	if err != nil {
		return nil, err
	}
	retItem := &image_group_api.ImageGroupInfo{}
	err = proto.Unmarshal(value, retItem)
	if err != nil {
		return nil, err
	}
	return retItem, nil
}

func (db *_ImageGroupDao) Update(ctx context.Context, group *image_group_api.ImageGroupInfo) error {
	value, err := proto.Marshal(group)
	if err != nil {
		return err
	}

	txn := db.dbh.NewTransaction(true)
	defer txn.Discard()

	err = txn.Set([]byte(group.GroupName), value)
	if err != nil {
		return err
	}
	return txn.Commit()
}

func (db *_ImageGroupDao) Remove(ctx context.Context, groupName string) error {
	txn := db.dbh.NewTransaction(true)
	defer txn.Discard()

	err := txn.Delete([]byte(groupName))
	if err != nil {
		return err
	}
	return txn.Commit()
}

func (db *_ImageGroupDao) List(ctx context.Context) ([]*image_group_api.ImageGroupInfo, error) {
	txn := db.dbh.NewTransaction(false)
	defer txn.Discard()

	iter := txn.NewIterator(badger.DefaultIteratorOptions)
	defer iter.Close()

	groupList := []*image_group_api.ImageGroupInfo{}
	for iter.Rewind(); iter.Valid(); iter.Next() {
		item := iter.Item()
		if item.IsDeletedOrExpired() {
			continue
		}
		value, err := item.ValueCopy(nil)
		if err != nil {
			return nil, err
		}
		group := &image_group_api.ImageGroupInfo{}
		err = proto.Unmarshal(value, group)
		if err != nil {
			return nil, err
		}
		groupList = append(groupList, group)
	}
	sort.Sort(sort.Reverse(ImageGroupList(groupList)))
	return groupList, nil
}
